<template>
  <div>
    <!-- 查询区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-card>
        <el-input
            v-model="enrollment.cid"
            placeholder="请输入CID查询"
            prefix-icon="Search"
            style="width: 200px; margin-right: 10px"
        />
        <el-input
            v-model="enrollment.uname"
            placeholder="请输入uname查询"
            prefix-icon="Search"
            style="width: 200px; margin-right: 10px"
        />
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格展示 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table
          :data="enrollment.tableData"
          border
          style="width: 100%"
          stripe
          @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55"/>

        <el-table-column label="编号" type="index" width="60" />
        <el-table-column label="课程ID" prop="cid">
          <template #default="scope">
            <router-link
                :to="{ name: 'a_enrollment_with_cid', params: { cid: scope.row.cid } }"
                style="color: #409EFF; cursor: pointer;"
            >
              {{ scope.row.cid }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="用户ID" prop="uid">
          <template #default="scope">
           <router-link
  :to="{ name: 'a_user_with_uid', params: { uid: scope.row.uid } }"
  style="color: #409EFF; cursor: pointer;"
>
  {{ scope.row.uid }}
</router-link>

          </template>
        </el-table-column>
        <el-table-column label="用户名" prop="uname" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                type="primary"
                :icon="Edit"
                size="small"
                @click="handleEdit(scope.row)"
            >编 辑</el-button>
            <el-button
                type="danger"
                :icon="Delete"
                size="small"
                @click="handleDelete(scope.row)"
            >删 除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="enrollment.pageNumber"
            v-model:page-size="enrollment.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="enrollment.total"
            background
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="enrollment.form.cid ? '编辑报名信息' : '新增报名信息'"
        v-model="enrollment.formVisible"
        width="500"
    >
      <el-form
          :model="enrollment.form"
          style="padding-right: 50px; padding-top: 20px;"
      >
          <el-form-item label="课程ID" label-width="100px">
            <el-input v-model="enrollment.form.cid" placeholder="请输入课程ID" />
          </el-form-item>
          <el-form-item label="用户ID" label-width="100px">
            <el-input v-model="enrollment.form.uid" placeholder="请输入用户ID" />
          </el-form-item>
          <el-form-item label="用户名" label-width="100px">
            <el-input v-model="enrollment.form.uname" placeholder="请输入用户名" />
          </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="enrollment.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, watch, computed, onMounted} from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'

const enrollment = reactive({
  cid: '',
  uname: '',
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  tableData: [],
  selectedRows: [], // 存储选中行数据
  formVisible: false,
  form: {
    cid: '',
    uid: '',
    uname: ''
  },
  isEditing: false
})

const route = useRoute()

// 计算属性：是否是编辑状态
const isEditing = computed(() => !!enrollment.form.cid)

// 监听路由参数变化
watch(() => route.params.cid, (newCid) => {
  if (newCid) {
    enrollment.cid = newCid
    load()
  }
}, { immediate: true })

// 加载数据
const load = () => {
  request.get('/v1/admin/selectPage', {
    params: {
      tableName: 'enrollment',
      id: enrollment.cid,
      name: enrollment.uname,
      pageNum: enrollment.pageNumber,
      pageSize: enrollment.pageSize
    }
  }).then(res => {
    console.log('响应数据:', res)
    if (res.state === 2001) {
      enrollment.tableData = res.data.list || []
      enrollment.total = res.data.total || 0
    } else {
      enrollment.tableData = []
      enrollment.total = 0
    }
  }).catch(error => {
    console.error('请求失败:', error)
    enrollment.tableData = []
    enrollment.total = 0
  })
}

// 组件挂载时自动加载数据
onMounted(() => {
  load()
})

// 重置查询条件
const reset = () => {
  enrollment.cid = ''
  enrollment.uname = ''
  load()
}

// 新增
const handleAdd = () => {
  enrollment.form = {
    cid: '',
    uid: '',
    uname: ''
  }
  enrollment.formVisible = true
}

// 编辑
const handleEdit = (row) => {
  enrollment.form = {
    cid: row.cid,
    uid: row.uid,
    uname: row.uname
  }
  enrollment.isEditing = true
  enrollment.formVisible = true
}
   // 删除单条记录
   const handleDelete = (row) => {
     ElMessageBox.confirm('确定要删除这条报名记录吗？', '提示', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     }).then(() => {
       request.delete('/v1/admin/delete', {
         data: {
           tableName: 'enrollment',
           id: row.cid,
           uid:row.uid
         }
       }).then(res => {
         if (res.state === 2001) {
           ElMessage.success('删除成功')
           load()
         } else {
           ElMessage.error('删除失败')
         }
       }).catch(error => {
         console.error('请求失败:', error)
         ElMessage.error('请求失败，请检查网络或服务器')
       })
     }).catch(() => {
       // 用户取消删除
     })
   }

// 批量删除
const handleBatchDelete = () => {
  if (enrollment.selectedRows.length === 0) {
    ElMessage.warning('请选择要删除的报名记录')
    return
  }
  
  const pairs = enrollment.selectedRows.map(row => ({
    cid: row.cid,
    uid: row.uid
  }));

  ElMessageBox.confirm('确定要批量删除这些报名记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/batchDelete', {
      data: {
        tableName: 'enrollment',
        pairs: pairs
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error('批量删除失败')
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage.error('请求失败，请检查网络或服务器')
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 表格多选变化
const handleSelectionChange = (rows) => {
  enrollment.selectedRows = rows
}

// 保存新增或编辑
const save = () => {
  const { cid, uid } = enrollment.form;

  if (!cid || !uid) {
    ElMessage.warning('课程ID和用户ID不能为空');
    return;
  }

  // 判断是新增还是编辑
  if (!enrollment.isEditing) {
    // 新增逻辑：先校验 cid & uid 是否存在
    request.get('/v1/admin/checkCidExist', { params: { cid } })
        .then(res => {
          if (!res.data) {
            ElMessage.error('课程不存在，请输入正确的CID');
            return Promise.reject();
          }
          return request.get('/v1/admin/checkUidExist', { params: { uid } });
        })
        .then(res => {
          if (!res.data) {
            ElMessage.error('用户不存在，请输入正确的UID');
            return;
          }

          // 开始新增
          return request.post('/v1/admin/add', {
            tableName: 'enrollment',
            data: enrollment.form
          });
        })
        .then(res => {
          if (res.state === 2001) {
            ElMessage.success('新增成功');
            enrollment.formVisible = false;
            load();
          } else {
            ElMessage.error('新增失败');
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          ElMessage.error('请求失败，请检查网络或服务器');
        });

  } else {
    // 编辑逻辑：只允许修改 uname，使用原始 cid + uid 更新
    request.put('/v1/admin/update', {
      tableName: 'enrollment',
      data: {
        cid: enrollment.form.cid,
        uid: enrollment.form.uid,
        uname: enrollment.form.uname
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage.success('编辑成功');
        enrollment.formVisible = false;
        load();
      } else {
        ElMessage.error('编辑失败');
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error('请求失败，请检查网络或服务器');
    });
  }
}
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
</style>
